
import {defineButton} from "./buttons.js";
import {report} from "../report.js";
import {tr} from "./translations.js";
import {ø} from "../util/objects.js";


/**
 * @param buttons d3 selection of one or more button elements
 * @param {Model} sharedStore
 */
export function defineShowCurrentPosition(buttons, sharedStore) {

    defineButton(buttons, function() {
        if (!navigator.geolocation) {
            report.status(tr`Finding current position is not supported`);
            return;
        }

        report.status(tr`Finding current position...`);
        const actor = this;

        function updateStore({coords}) {
            const λ = +coords.longitude;
            const φ = +coords.latitude;
            if (λ === λ && φ === φ) {
                const orientation = ø(sharedStore.get("orientation") ?? {}, {rotate: [-λ, -φ]});
                sharedStore.save({spotlight_coords: [λ, φ], orientation}, {actor});
            }
            report.reset();
        }

        new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition(resolve, reject))
            .then(updateStore)
            .catch(report.error);
    });

}
